import shapelib
import dbflib

class SHPReader():
    '''read shapefile
    Class attributes: Shapefile shp: the read shape file
                      Dictionary shpDict: {shpID: shape's coordinate list}
                      Integer shpNum: the number of shapes
                      Integer shpType: the type of shapes
                      Double shpMinX: the min of shapes' X coordinates
                      Double shpMinY: the min of shapes' Y coordinates
                      Double shpMaxX: the max of shapes' X coordinates
                      Double shpMaxY: the max of shapes' Y coordinates'''
    
    def __init__(self,filepath):
        '''construction function: initialize the instance of Class shpReader 
        input: the file path of shape file
        '''    
        self.shp=shapelib.ShapeFile(filepath)
        self.dbf=dbflib.DBFFile(filepath.split('.')[0]+'.dbf')
        shpDbf=self.setShpDbfDict()
        self.shpDict=shpDbf[0]
        self.dbfDict=shpDbf[1]
        self.fieldNames=shpDbf[2]
        self.shpNum=self.setShpNum()
        self.shpType=self.setShpType()
        self.shpMinX=self.setShpMinX()
        self.shpMinY=self.setShpMinY()
        self.shpMaxX=self.setShpMaxX()
        self.shpMaxY=self.setShpMaxY()

    
    def setShpDbfDict(self):
        shapeDict={}
        dbfDict={}
        print self.shp.info()[0]
        for i in range(self.shp.info()[0]):
            shapeDict[i]=self.shp.read_object(i).vertices()[0]
            dbfDict[i]=self.dbf.read_record(i)
        
        fieldNames=[]
        for j in range(self.dbf.field_count()):
            fieldNames.append(self.dbf.field_info(j)[1])
            
        return [shapeDict,dbfDict, fieldNames]
    
    def setShpNum(self):
        return self.shp.info()[0]
    
    def setShpType(self):
        shapeTypeNum=self.shp.info()[1]
        shapeTypeDict={3: 'SHPT_ARC',
                   23: 'SHPT_ARCM',
                   13: 'SHPT_ARCZ',
                   31: 'SHPT_MULTIPATCH',
                   8: 'SHPT_MULTIPOINT',
                   28: 'SHPT_MULTIPOINTM',
                   18: 'SHPT_MULTIPOINTZ',
                   0: 'SHPT_NULL',
                   1: 'SHPT_POINT',
                   21: 'SHPT_POINTM',
                   11: 'SHPT_POINTZ',
                   5: 'SHPT_POLYGON',
                   25: 'SHPT_POLYGONM',
                   15: 'SHPT_POLYGONZ'}
        return shapeTypeDict[shapeTypeNum]
    
    def setShpMinX(self):
        return self.shp.info()[2][0]

    def setShpMinY(self):
        return self.shp.info()[2][1]
    
    def setShpMaxX(self):
        return self.shp.info()[3][0]    
    
    def setShpMaxY(self):
        return self.shp.info()[3][1]     

    
    
    
    
    
    
    